const pagesList = require('../readerPages/index.js').getPagesPath
const loaderUtils = require('loader-utils')
const UtilsIndex = require('../utils/index.js')
// 遍历
const traverse = require('babel-traverse').default;
const t = require('babel-types');
const DefaultData = require("../utils/DefaultData.js");

let defaultOptions = {
  importPath: 'import pageConsole from \'@/webpackPlugin/pageConsole/pageConsoleText.vue\';',
  pageConsole: 'pageConsole',
  needRun: () => {
    return true
  },
  getPlugins: () => {
    return DefaultData.jsAstPlugins
  }
}

class PageConsole {
  static getPageScript(pageCode) {
    const load = UtilsIndex.getHtmlLoad(pageCode)
    return load('script').html()
  }

  static changeTemCode(pageCode) {
    const load = UtilsIndex.getHtmlLoad(pageCode)
    load('template view').append(`<${defaultOptions.pageConsole} ref="xzxPageConsoleRef"/>`).html()
    return load.html()
  }
  static getScriptAst(scriptCode) {
    return UtilsIndex.getScriptAst(scriptCode,defaultOptions.getPlugins())
  }

  static getAstSyncCode(scriptAst) {
    return UtilsIndex.getAstSyncCode(scriptAst,defaultOptions.getPlugins())
  }

  static changeScriptCode(scriptCode, addCom = false) {
    const ast = PageConsole.getScriptAst(scriptCode)
    if (addCom) {
      traverse(ast, {
        ExportDefaultDeclaration(ipath) {
          let {node} = ipath
          node = node.declaration
          if (node.type === 'ObjectExpression') {
            const find = node.properties.find(i => i.key.name === 'components' && i.type === 'ObjectProperty')
            const addConsole = t.objectProperty(t.identifier(defaultOptions.pageConsole), t.identifier(defaultOptions.pageConsole));
            if (find) { // 找到了components
              let pageConsole = find.value.properties.find(i => i.key.name === defaultOptions.pageConsole)
              if (!pageConsole) {
                find.value.properties.push(addConsole)
              }
            } else {
              node.properties.push(t.objectProperty(t.identifier('components'), t.objectExpression([addConsole])))
            }
            const findShowFunc = node.properties.find(i => i.key.name === 'onShow' && i.type === 'ObjectMethod')
            const runFunc = 'this.$nextTick(()=>{\n' +
              '        this.$refs.xzxPageConsoleRef._showInit()\n' +
              '      })'
            const runFuncAst = PageConsole.getScriptAst(runFunc)
            const runFuncNode = runFuncAst.program.body[0]
            if (findShowFunc) {
              const find = findShowFunc.body.body.find(i => {
                const substring = scriptCode.substring(i.start, i.end);
                if (substring === runFunc) {
                  return true
                } else {
                  return false
                }
              })
              if(!find) {
                findShowFunc.body.body.push(runFuncNode)
              }
            } else {
              const key = t.identifier("onShow")
              const body = t.blockStatement(runFuncAst.program.body)
              const showMethod = t.objectMethod("method",key,[],body)
              node.properties.push(showMethod)
            }
          }
        }
      })
    }
    return PageConsole.getAstSyncCode(ast)
  }

  static changeCode(source, path = '') {
    if (pagesList().includes(path)) {
      const script = PageConsole.getPageScript(source)
      let changeScript = PageConsole.changeScriptCode(script, true)
      changeScript = '\n' + defaultOptions.importPath + '\n' + changeScript + '\n'
      source = source.replace(script, changeScript)
      source = PageConsole.changeTemCode(source)
    }
    return source
  }
}

module.exports = function (source) {
  // 获取到用户给当前 Loader 传入的 options
  defaultOptions = Object.assign(defaultOptions, loaderUtils.getOptions(this))
  const {resourcePath} = this
  if (!defaultOptions.needRun()) {
    return source
  }
  return PageConsole.changeCode(source, resourcePath)
}
